let num = 0;
let _total;

function getOrderInfo() {
    $.ajax({
        type: 'get',
        url: '/order/queryOrder',
        dataType: 'json',
        success: function(data) {
            let html = template("OrderTpl", { data: getCartItemCount(data) });
            num = data.length;
            $("#orderNum").html(html);
        }
    });
}

$(document).ready(
    function() {
        getOrderInfo();
        getAddressInfo();
        setTimeout(caltotal, 100);
    }
);


function getAddressInfo() {
    $.ajax({
        type: 'get',
        url: '/address/queryAddress',
        dataType: 'json',
        success: function(data) {
            let html = template("addressTpl", { data });
            $("#address").html(html);
            let html2 = template("addressNowTpl", { data });
            $("#addressaaa").html(html2);
        }
    });
}


function getCartItemCount(data) {
    // js数组对象相同值相加，不同添加
    var newArr = [];
    data.forEach(item => {
        var dataItem = item;
        if (newArr.length > 0) {
            var filterValue = newArr.filter(v => {
                return v.productId == dataItem.productId
            })
            if (filterValue.length > 0) {
                newArr.forEach(n => {
                    if (n.productId == filterValue[0].productId) {
                        n.num = filterValue[0].num + dataItem.num;
                    }
                })
            } else {
                newArr.push(dataItem)
            }
        } else {
            newArr.push(dataItem)
        }

    });
    return newArr


}


function caltotal() {
    var total = document.getElementsByClassName("shop_total");
    let sum = 0;
    for (let i = 0; i < total.length; i++) {
        sum += parseInt(total[i].innerHTML);;
    }
    sum += 10;
    if (document.getElementsByName("delevery").checked) {
        sum += 1.23;
    }
    _total = sum;
    document.getElementById("sum").innerHTML = sum.toFixed(2);
    document.getElementById("total").innerHTML = sum.toFixed(2);
}

function button() {
    alert("提交成功");
    setTimeout(() => {
        location.href = "shop.html"
    }, 1000)
}

function changeToatl() {
    let sum = _total;
    if (document.getElementById("delevery").checked == true) {
        sum = _total + 1.23;
    } else {
        sum = _total;
    }
    console.log(sum);
    console.log("_total:" + _total);
    document.getElementById("sum").innerHTML = sum.toFixed(2);
    document.getElementById("total").innerHTML = sum.toFixed(2);
}